/**
 * 
 */
package com.hawkfly.interceptor;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;

import com.wbcs.config.component.application.report.ReportBean;
import com.wbcs.jbsf.dao.IDataModal;
import com.wbcs.jbsf.dao.JBSFDaoTemplate;
import com.wbcs.jbsf.util.Wbcs4JBSFUtil;
import com.wbcs.system.ReportRequest;
import com.wbcs.system.assistant.EditableReportAssistant;
import com.wbcs.system.component.application.report.configbean.editablereport.AbsEditActionBean;
import com.wbcs.system.component.application.report.configbean.editablereport.AbsEditableReportEditDataBean;
import com.wbcs.system.component.application.report.configbean.editablereport.DeleteSqlActionBean;
import com.wbcs.system.component.application.report.configbean.editablereport.EditableReportInsertDataBean;
import com.wbcs.system.component.application.report.configbean.editablereport.InsertSqlActionBean;
import com.wbcs.system.component.application.report.configbean.editablereport.UpdateSqlActionBean;
import com.wbcs.system.intercept.AbsInterceptorDefaultAdapter;
import com.wbcs.system.intercept.IInterceptor;

/**
 * 仅用于from报表类型
 * @author hawkfly
 *
 */
public class ItprParseParamsToUpdateURoles extends AbsInterceptorDefaultAdapter
{
    private JBSFDaoTemplate daoTemplate = new JBSFDaoTemplate(false);
    
    @Override
	public int doSavePerAction(ReportRequest rrequest,ReportBean rbean,Map<String,String> mRowData,Map<String,String> mParamValues,
            AbsEditActionBean actionbean,AbsEditableReportEditDataBean editbean)
    {   
        if(editbean instanceof EditableReportInsertDataBean){
            if(actionbean instanceof InsertSqlActionBean){
                return Wbcs4JBSFUtil.doSavePerAction(rrequest, rbean, mRowData, mParamValues, actionbean, editbean, "rolecode2", new String[]{"USERCODE","USERCODE","USERCODE__old"});
            }else
                return EditableReportAssistant.getInstance().doSavePerAction(rrequest,rbean,mRowData,mParamValues,actionbean,editbean);
        }else{
            if(actionbean instanceof InsertSqlActionBean){
                return Wbcs4JBSFUtil.doSavePerAction(rrequest, rbean, mRowData, mParamValues, actionbean, editbean, "rolecode", new String[]{"USERCODE","USERCODE","USERCODE__old","USERCODE"});
            }else if(actionbean instanceof DeleteSqlActionBean){
                return Wbcs4JBSFUtil.doSavePerAction(rrequest, rbean, mRowData, mParamValues, actionbean, editbean, "rolecode", new String[]{"USERCODE","USERCODE","USERCODE__old"});
            }else if(actionbean instanceof UpdateSqlActionBean){//处理密码字段MD5加密重复更新问题
                UpdateSqlActionBean updateSqlActionBean = (UpdateSqlActionBean)actionbean;
                String sql = updateSqlActionBean.getSql();
                String password = mRowData.get("password");
                String password__old = mRowData.get("password__old");
                if(password__old != null && password__old.equals(password) && sql.indexOf("FN_MD5") != -1)//不再执行MD5加密函数
                {
                    String newsql = sql.replace("FN_MD5( ? )"," ? ");
                    updateSqlActionBean.setSql(newsql);
                }
                return EditableReportAssistant.getInstance().doSavePerAction(rrequest,rbean,mRowData,mParamValues,actionbean,editbean);
            }else
                return EditableReportAssistant.getInstance().doSavePerAction(rrequest,rbean,mRowData,mParamValues,actionbean,editbean);
        }
        
    }
    /*如果usercode已经存在则执行自己的update操作，否则执行原始配置SQL*/
    @Override
	public int doSavePerRow(ReportRequest rrequest,ReportBean rbean,Map<String,String> mRowData,Map<String,String> mParamValues,
            AbsEditableReportEditDataBean editbean)
    {
    	Connection conn = rrequest.getConnection();
    	try{
        if(editbean instanceof EditableReportInsertDataBean){//添加动作
            String usercode = mRowData.get("USERCODE");
            if(hasusercode(rrequest, usercode)){//用户已存在
                int updateuserffectRow = 0; int insertuserexteffectRow = 0; int insertghostroleeffectRow = 0;
                String updateusersql = "update t_user_info set isadminuser = '1' where username = ?";
                updateuserffectRow = daoTemplate.update(updateusersql,rrequest.getConnection(),usercode);
                String islock = mRowData.get("islock"); String startlifetime = mRowData.get("startlifetime"); String endlifetime = mRowData.get("endlifetime");
                /*String id = mRowData.get("ID");//由于ID的displaytype="hidden"这里无法得到数据*/
                String seqid = mParamValues.get("seqid");
                String insertuserextsql = "insert into jbsf_e_users(id, userid, islock, startlifetime, endlifetime) values(?,?,?,?,?)";
                insertuserexteffectRow = daoTemplate.update(insertuserextsql,rrequest.getConnection(),seqid, usercode, islock==null?"0":islock, startlifetime, endlifetime);
                String getidsql = "select id from t_user_info where username=?";
                String id = daoTemplate.select(getidsql,conn,new IDataModal<String>(){
                    public String loadDatas(ResultSet rs,int ccount,ResultSetMetaData rmd,String dataModal) throws SQLException
                    {
                        while(rs.next()){
                            dataModal = String.valueOf(rs.getInt(1));
                        }
                        return dataModal;
                    }},usercode);
                String crid = mParamValues.get("crid");
                String insertghostrolesql = "insert into jbsf_roles(id,code,description,createrolecode,isghost) values(?,?,?,?,?)";
                insertghostroleeffectRow = daoTemplate.update(insertghostrolesql,rrequest.getConnection(),id, usercode, "幽灵角色", crid, "1");
                /*String usercode__code = mRowData.get("USERCODE__old");
                String rolecode = mRowData.get("rolecode");
                String rolecode2 = mRowData.get("rolecode2");
                String insertuserrolerltsql = "insert into jbsf_r_rolesusers(rolecode, usercode) (select ID, ? usercode from jbsf_roles where id in (?) minus select to_number(rolecode), ? usercode from jbsf_r_rolesusers where usercode=?)";
                insertuserrolerlteffectRow = daoTemplate.update(insertuserrolerltsql,rrequest.getConnection(),usercode, rolecode2, rolecode, usercode__code);*/
                if(updateuserffectRow != 0 && insertuserexteffectRow != 0 && insertghostroleeffectRow != 0)
                    return IInterceptor.WX_RETURNVAL_SUCCESS;
                else return IInterceptor.WX_RETURNVAL_TERMINATE;
            }else{//用户不存在
                return EditableReportAssistant.getInstance().doSaveRow(rrequest,rbean,mRowData,mParamValues,editbean);
            }
        }else{//删除，修改动作
            return EditableReportAssistant.getInstance().doSaveRow(rrequest,rbean,mRowData,mParamValues,editbean);
        }
    	}catch(SQLException e){
    		e.printStackTrace();
    		try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
    		return WX_RETURNVAL_TERMINATE;
    	}
    }
    
    boolean hasusercode(ReportRequest rrequest,String usercode) throws SQLException{
        boolean returnval = false;
        String sql = "select count(1) from t_user_info where username=?";
        returnval = daoTemplate.select(sql,rrequest.getConnection(),new IDataModal<Boolean>(){
            public Boolean loadDatas(ResultSet rs,int ccount,ResultSetMetaData rmd,Boolean dataModal) throws SQLException
            {
                int rowcount = 0;
                while(rs.next()){
                    rowcount = rs.getInt(1);
                }
                if(rowcount > 0)return true;
                else return false;
            }
        },usercode);
        
        return returnval;
    }
}

